using Google.Protobuf;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProtobufMessagePool
{
    Stack<global::Google.Protobuf.IMessage> stack;
    int maxCapacity;
    System.Func<global::Google.Protobuf.IMessage> creator;
    public ProtobufMessagePool(System.Func<global::Google.Protobuf.IMessage> creator,int capacity = 32)
    {
        if(capacity < 32)
            capacity = 32;
        maxCapacity = capacity * 2;
        stack = new Stack<global::Google.Protobuf.IMessage>(capacity);
        this.creator = creator;
    }

    public global::Google.Protobuf.IMessage Get()
    {
        if(stack.Count > 0)
            return stack.Pop();
        return creator();
    }

    public void Put(global::Google.Protobuf.IMessage handle)
    {
        if(null != handle)
        {
            if (stack.Count < maxCapacity)
            {
                stack.Push(handle);
            }
#if UNITY_EDITOR
            else
            {
                Debug.LogWarning($"{handle.GetType().Name}:Pooled Items Out Of Max Capacity Range [{maxCapacity}]");
            }
#endif
        }
    }
}
